home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 7080 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.6 KB  |  86 lines

  1. Path: news.mistral.co.uk!usenet
  2. From: alanc@mistral.co.uk (Alan Campbell)
  3. Newsgroups: comp.lang.c++
  4. Subject: Any way to restrict casting?
  5. Date: Wed, 21 Feb 1996 18:12:43 GMT
  6. Organization: Me! Organized?,  I don't think so!
  7. Message-ID: <4gfuj4$1cu@news.mistral.co.uk>
  8. NNTP-Posting-Host: l74.mistral.co.uk
  9. X-Newsreader: Forte Free Agent 1.0.82
  10.  
  11. Using Borland C++ 3.1, I find I can coerce a pointer to an instance of
  12. a class into a pointer to *anything*.  Like an int.  
  13.  
  14. e.g.:
  15.  
  16. #include <iostream.h>
  17. #include <string.h>
  18.  
  19. class Base {
  20.  
  21. public:
  22.    int iFieldb;
  23.    char cFieldb;
  24.    char sFieldb[10];
  25.  
  26. };
  27.  
  28. class Derived: public Base {
  29.  
  30. public:
  31.    int iFieldd;
  32.    char cFieldd;
  33.    char sFieldd[10];
  34. };
  35.  
  36.  
  37. int main()
  38.   {
  39.  
  40.    Base aBase;
  41.    Derived aDerived;
  42.  
  43.    aBase.iFieldb = 10;
  44.    aBase.cFieldb = 'a';
  45.    strcpy(aBase.sFieldb,"abcdefghi");
  46.  
  47.    aDerived.iFieldd = 210;
  48.    aDerived.cFieldd = 'ba';
  49.    strcpy(aDerived.sFieldd,"jklmnopqr");
  50.  
  51.    Base* ptrBase = &aBase;
  52.    cout << "aDerived's sFieldb: " <<  ptrBase->sFieldb  << endl;
  53.  
  54.    Derived*  ptrDerived = &aDerived;
  55.    cout << "aDerived's sFieldd: " << ptrDerived->sFieldd  << endl;
  56.  
  57. // this is stupid, but it works
  58.  
  59.    ptrDerived =  (Derived*) ptrBase;
  60.  
  61.    cout << "aBase's sFieldd, treated as a Derived: " <<
  62.      ptrDerived->sFieldd  << endl;
  63.  
  64.    int anInt;
  65.  
  66. // this is even stupider; taking a data member of an int!
  67.  
  68.    ptrDerived =  (Derived*) &anInt;
  69.    cout << "anInt's sFieldd, treated as a Derived: " <<
  70.      ptrDerived->sFieldd  << endl;
  71.  
  72.    return 1;
  73.  
  74.   };
  75.  
  76. Is this valid in all dialects of C++?  Is it part of the standard?  If
  77. so, ouch.  
  78.  
  79. Yours,
  80.  
  81. Alan Campbell
  82. Brighton, UK
  83.  
  84. <<<<<<<<<<<<<<<<<<<<<<     >>>>>>>>>>>>>>>>>>>
  85.  
  86.